package com.zjhome.itoken.service.sso.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.zjhome.itoken.common.domain.TbSysUser;
import com.zjhome.itoken.common.utils.MapperUtils;
import com.zjhome.itoken.service.sso.mapper.TbSysUserMapper;
import com.zjhome.itoken.service.sso.service.LoginService;
import com.zjhome.itoken.service.sso.service.consumer.RedisService;

import tk.mybatis.mapper.entity.Example;

/**
 * 登陆业务实现
 * 
 * @author 0283000121
 *
 */
@Service
public class LoginServiceImpl implements LoginService {
	private final Logger logger = LoggerFactory.getLogger(LoginServiceImpl.class); 
	
	@Autowired
	private TbSysUserMapper tbSysUserMapper;
	
	@Autowired
	private RedisService	redisService;

	@Override
	public TbSysUser login(String loginCode, String plantPassword)  {
		TbSysUser tbSysUser = null;
		// 先尝试通过redis 查询用户信息
		String json = redisService.get(loginCode);
		if (json == null) {
			// 不在缓存中
			// 用户登陆
			Example example = new Example(TbSysUser.class);
			example.createCriteria().andEqualTo("loginCode", loginCode);

			tbSysUser = tbSysUserMapper.selectOneByExample(example);
			if (tbSysUser != null) {
				String password = DigestUtils.md5DigestAsHex(plantPassword.getBytes());

				if (password.equals(tbSysUser.getPassword())) {
					// 密码匹配
					// 更新到缓存中
					try {
						redisService.put(loginCode, MapperUtils.obj2json(tbSysUser), 60*60*24);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}	// 保存一天
					return tbSysUser;
				}
				else {
					// 密码不匹配
					return null;
				}
			}

		}
		else {
			// 缓存命中
			try {
				tbSysUser = MapperUtils.json2pojo(json, TbSysUser.class);
			} catch (Exception e) {
				// TODO Auto-generated catch block
//				e.printStackTrace();
				logger.warn("触发熔断: {}", e.getMessage());
			}
		}

		return tbSysUser;
	}

}
